package file

import (
	"errors"
	"fmt"
	"kubeInstall/pkg/client/db"
	"kubeInstall/server/models/file"
	"kubeInstall/utils/uuid"
)

func Get(packageId string) (*file.SysPackage, error) {
	var sysPackage file.SysPackage

	err := db.Db.Where("package_id = ?", packageId).First(&sysPackage).Error

	if err != nil {
		if err == db.ErrRecordNotFound {
			return nil, fmt.Errorf("package ID %s not found", packageId)
		}
		return nil, err
	}

	return &sysPackage, nil
}

func GetPackageList(limit, Offset int) ([]*file.SysPackage, error) {
	var pkgs []*file.SysPackage
	if limit == 0 {
		limit = 10
	}

	err := db.Db.Select("*").Limit(limit).Offset((Offset - 1) * limit).Find(&pkgs).Error

	if err != nil && err != db.ErrRecordNotFound {
		return nil, err
	}

	return pkgs, nil

}

/*func DeleteFile(imageId string) error {
	var sysPackage SysPackage
	err := Db.Where("package_id = ?", imageId).Delete(&sysPackage).Error

	return err
}*/

func CreateFile(f file.SysPackage) (file.SysPackage, error) {
	//判断文件是否存在
	var count int

	db.Db.Model(f).Where("name = ?&& size = ?", f.Name, f.Size).Count(&count)
	if count > 1 {
		return f, errors.New(fmt.Sprintf("system package: %s already exsist", f.Name))
	}

	//插入数据，并返回。
	f.ID = uuid.GenUUID()
	if err := db.Db.Create(&f).Error; err != nil {
		return f, err
	}
	return f, nil
}

func UpdateFile(packageId string, f *file.SysPackage) error {
	err := db.Db.Model(&file.SysPackage{}).Where("package_id = ?", packageId).Update(&f).Error
	return err
}
